<template>
  <div class="contentView" v-loading="formLoading" :style="`height:${contentHeight}px`">
    <div class="routeHeader">
      <el-button
        class="mr-5px"
        @click="submitForm(1)"
        type="primary"
        :disabled="formLoading"
        v-hasPermi="['technology:design-alert-ticket:save']"
        v-show="!isDis()"
        >保 存</el-button
      >
      <el-button
        class="mr-5px"
        @click="submitForm(2)"
        type="primary"
        :disabled="formLoading"
        v-hasPermi="['technology:design-alert-ticket:submit']"
        v-show="!isDis()"
        >提 交</el-button
      >
      <el-button
        class="mr-5px"
        @click="submitForm(3)"
        type="danger"
        plain
        :disabled="formLoading"
        v-hasPermi="['technology:design-alert-ticket:cancel']"
        v-show="formType == 'edit' && formData.dictAlertTicketStatus == 30"
        >作废</el-button
      >
      <el-button @click="goBack">关 闭</el-button>
    </div>
    <el-scrollbar :style="`height:${contentHeight - 63}px`">
      <div class="orderTitle">
        <img src="@/assets/imgs/hasColorLogo.png" />
        设计变更单
      </div>
      <el-row class="orderView" v-loading="formLoading">
        <el-col :span="24" class="detailTitle">基本信息</el-col>
        <el-col :span="6" class="detailItem">
          <span class="leftLabel">任务单号<span style="color: red">*</span></span>
          <el-input class="rightIpt" v-model="formData.taskNumber" readonly>
            <template #suffix>
              <Icon icon="ep:search" @click="showOrderNum" />
            </template>
          </el-input>
        </el-col>
        <el-col :span="6" class="detailItem">
          <span class="leftLabel">产品编号</span>
          <el-input class="rightIpt" v-model="formData.productNumber" disabled />
        </el-col>
        <el-col :span="6" class="detailItem">
          <span class="leftLabel">产品名称</span>
          <el-input class="rightIpt" v-model="formData.productName" disabled />
        </el-col>
        <el-col :span="6" class="detailItem">
          <span class="leftLabel">部件类型</span>
          <el-input class="rightIpt" v-model="formData.partType" disabled />
        </el-col>
        <el-col :span="6" class="detailItem" style="border-left: none">
          <span class="leftLabel">客户代码</span>
          <el-input class="rightIpt" v-model="formData.customerCode" disabled />
        </el-col>
        <el-col :span="6" class="detailItem">
          <span class="leftLabel">变更原因<span style="color: red">*</span></span>
          <el-select
            v-model="formData.dictAlertReason"
            placeholder=""
            class="rightIpt"
            :disabled="isDis()"
          >
            <el-option
              v-for="dict in getIntDictOptions('dict_alert_reason')"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-col>
        <el-col :span="6" class="detailItem">
          <span class="leftLabel">变更图纸数<span style="color: red">*</span></span>
          <el-input class="rightIpt" v-model="formData.alertDrawingQuantity" :disabled="isDis()" />
        </el-col>
        <el-col :span="6" class="detailItem">
          <span class="leftLabel">现状调查<span style="color: red">*</span></span>
          <el-select
            v-model="formData.dictActualitySurvey"
            placeholder=""
            class="rightIpt"
            :disabled="isDis()"
          >
            <el-option
              v-for="dict in getIntDictOptions('dict_actuality_survey')"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-col>
        <el-col
          :span="24"
          class="detailTitle"
          style="display: flex; justify-content: space-between; align-items: center"
        >
          <span>变更项明细</span>
          <el-button class="mr-5px" @click="addCol" type="primary" size="small" :disabled="isDis()"
            >新增行</el-button
          >
        </el-col>
        <el-table
          ref="singleTableRef"
          :data="formData.details"
          style="width: 100%"
          border
          class="tableView"
        >
          <el-table-column
            v-for="item in tableTitle"
            :key="item.val"
            :prop="item.val"
            :label="item.label"
            :width="item.width"
            align="left"
          >
            <template #header="{ column }">
              <template v-if="column.label == '图纸图号'"
                ><span style="color: red">*</span></template
              >
              {{ column.label }}
            </template>
            <template #default="scope">
              <!-- 字典 -->
              <template v-if="item.dictType">
                <!-- 直接翻译 -->
                <dict-tag
                  v-if="
                    ['dictInternalWork', 'dictOutsourcing', 'dictOutsidePurchase'].includes(
                      item.val
                    )
                  "
                  :type="item.dictType"
                  :value="scope.row[item.val]"
                />
                <!-- 需要操作 -->
                <el-select
                  v-else
                  v-model="scope.row[item.val]"
                  placeholder=""
                  :disabled="isDis()"
                  clearable
                >
                  <el-option
                    v-for="dict in getIntDictOptions(item.dictType)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </template>

              <!-- 非字典 -->
              <template v-else>
                <el-input v-nextInput="'drawingNumber'"  name="drawingNumber" v-if="item.val == 'drawingNumber'" v-model="scope.row[item.val]" readonly>
                  <template #suffix>
                    <Icon icon="ep:search" @click="showDrawingNumber(scope)" />
                  </template>
                </el-input>
                <el-input
                  v-nextInput="item.val"  
                  :name="item.val"
                  v-else-if="['newDrawingNumber', 'newPartName', 'newQuantity'].includes(item.val)"
                  v-model="scope.row[item.val]"
                  placeholder="请输入"
                  class="tableIpt"
                  :disabled="isDis()"
                />
                <template v-else>{{ scope.row[item.val] }}</template>
              </template>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" align="left" fixed="right">
            <template #default="scope">
              <el-button
                size="small"
                link
                type="danger"
                @click="delTableCol(scope.$index)"
                :disabled="isDis()"
                >移除行</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-col :span="24" class="detailTitle" style="border-top: 1px solid #000">其他说明</el-col>
        <el-input
          :disabled="formType == 'look' || (formType == 'edit' && formData.status == 10)"
          resize="none"
          v-model="formData.otherDescription"
          :rows="6"
          type="textarea"
        />
        <el-col :span="24" class="detailTitle">审批结果</el-col>
        <el-input
          disabled
          resize="none"
          v-model="formData.approverOpinion"
          :rows="3"
          type="textarea"
        />
      </el-row>
    </el-scrollbar>
    <!-- 选择任务单 -->
    <TaskForm @getVerifyParams="getVerifyParams" ref="taskForm" />
    <!-- 图纸图号 -->
    <drawingNumber @slectRes="slectRes" ref="drawingNumberForm" />
  </div>
</template>
<script setup lang="ts">
   import { getIntDictOptions } from '@/utils/dict'
   import * as DesignAlertTicketApi from '@/api/technology/designAlertTicket'
   import { useTagsViewStore } from '@/store/modules/tagsView'
   const { t } = useI18n() // 国际化
   const message = useMessage() // 消息弹窗
   //任务单号
   import TaskForm from '../designCompleteTicket/taskForm.vue'
   //图纸图号
   import drawingNumber from './drawingNumber.vue'
   const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
   const formType = ref('') // 表单的类型：create - 新增；update - 修改
   const formData = ref({
     details: []
   })
   const tableTitle = ref([
     {
       label: '图纸图号',
       val: 'drawingNumber',
       width: 160
     },
     {
       label: '部件编码',
       val: 'partNumber',
       width: 160
     },
     {
       label: '部件名称',
       val: 'partName',
       width: 160
     },
     {
       label: '规格',
       val: 'specification',
       width: 100
     },
     {
       label: '内作',
       val: 'dictInternalWork',
       width: 60,
       dictType: 'is_machining'
     },
     {
       label: '外协',
       val: 'dictOutsourcing',
       width: 60,
       dictType: 'is_machining'
     },
     {
       label: '外购',
       val: 'dictOutsidePurchase',
       width: 60,
       dictType: 'is_machining'
     },
     {
       label: '数量',
       val: 'quantity',
       width: 60
     },
     {
       label: '目前状态',
       val: 'currentState',
       width: 160
     },
     {
       label: '填写人',
       val: 'writtenBy',
       width: 150
     },
     {
       label: '图纸变更方案',
       val: 'dictAlertPlan',
       width: 160,
       dictType: 'dict_alert_plan'
     },
     {
       label: '新图纸图号',
       val: 'newDrawingNumber',
       width: 160
     },
     {
       label: '新零部件名称',
       val: 'newPartName',
       width: 160
     },
     {
       label: '数量',
       val: 'newQuantity',
       width: 80
     },
     {
       label: '部件处理方案',
       val: 'dictHandlePlan',
       width: 160,
       dictType: 'dict_handle_plan'
     }
   ])
   //选择任务单号
   const taskForm = ref() //选择任务单ref
   const showOrderNum = () => {
     if (isDis()) return
     taskForm.value.open()
   }
   // 任务单号回显
   const getVerifyParams = async (arr) => {
     console.log('arr', arr)
     const {
       id,
       taskNumber,
       productNumber,
       productName,
       partType,
       customerCode,
       customerName,
       productType,
       productStandard
     } = arr[0]
     formData.value.taskNumber = taskNumber
     formData.value.productNumber = productNumber
     formData.value.productName = productName
     formData.value.partType = partType
     formData.value.customerCode = customerCode
     formData.value.customerName = customerName
     formData.value.productType = productType
     formData.value.productStandard = productStandard
     formData.value.taskId = id
   }
   //显示图纸图号
   const drawingNumberForm = ref()
   const showDrawingNumber = (data: object) => {
     console.log(data)
     if (isDis()) return
     if (roleList.value.includes(formData.value.productNumber)) {
       message.error('请先选择任务单号')
       return
     }
     let obj = {
       index: data.$index,
       productNumber: formData.value.productNumber,
       partType: formData.value.partType
     }
     if (!roleList.value.includes(data.row.drawingNumber)) {
       obj.list = [data.row]
     }
     drawingNumberForm.value.open(obj)
   }
   //图纸图号结果
   const slectRes = (data: object) => {
     console.log(data)
     const {
       sourceId,
       drawingNumber,
       partNumber,
       partName,
       specification,
       dictInternalWork,
       dictOutsourcing,
       dictOutsidePurchase,
       quantity
     } = data.list[0]
     formData.value.details[data.index].sourceId = sourceId
     formData.value.details[data.index].drawingNumber = drawingNumber
     formData.value.details[data.index].partNumber = partNumber
     formData.value.details[data.index].partName = partName
     formData.value.details[data.index].specification = specification
     formData.value.details[data.index].dictInternalWork = dictInternalWork
     formData.value.details[data.index].dictOutsourcing = dictOutsourcing
     formData.value.details[data.index].dictOutsidePurchase = dictOutsidePurchase
     formData.value.details[data.index].quantity = quantity
   }
   //是否禁用
   const isDis = () => {
     if (formType.value == 'look') {
       //查看
       return true
     } else if (['create','jump'].includes(formType.value)) {
       //创建
       return false
     } else {
       //20-不通过、30-编辑中、40-待提交
       if ([20, 30,40].includes(formData.value.dictAlertTicketStatus)) {
         return false
       }
       return true
     }
   }
   //表格是否禁用
   //  const tableIsDis = () => {
   //    if (formType.value == 'look') {
   //      //查看
   //      return true
   //    }

   //  }
   /**新增行 */
   const addCol = () => {
     if (roleList.value.includes(formData.value.taskNumber)) {
       message.error('请选择任务单号')
       return
     }
     formData.value.details.push({
       drawingNumber: undefined,
       partNumber: undefined,
       partName: undefined,
       specification: undefined,
       dictInternalWork: undefined,
       dictOutsourcing: undefined,
       dictOutsidePurchase: undefined,
       quantity: undefined,
       currentState: undefined,
       dictAlertPlan: undefined,
       newDrawingNumber: undefined,
       newPartName: undefined,
       newQuantity: undefined,
       dictHandlePlan: undefined
     })
   }
   /**移除行 */
   const delTableCol = (index: number) => {
     formData.value.details.splice(index, 1)
   }
   /**返回 */
   const tagsViewStore = useTagsViewStore()
   const route = useRouter() // 路由
   const goBack = async () => {
     //获取当前路由并删除tagView
     tagsViewStore.delView(route.currentRoute.value)
     //跳转列表页
     route.push({
       path: '/technology/technology/drawingProduction/designAlertTicket'
     })
   }
   /** 提交表单 */
   const roleList = ref([undefined, null, ''])
   const submitForm = async (type: Number) => {
     const data = formData.value as unknown as DesignAlertTicketApi.DesignAlertTicketVO
     if (roleList.value.includes(data.taskNumber)) {
       message.error('任务单号不能为空')
       return
     }
     if (roleList.value.includes(data.dictAlertReason)) {
       message.error('请选择变更原因')
       return
     }
     if (roleList.value.includes(data.alertDrawingQuantity)) {
       message.error('交易图纸数不能为空')
       return
     }
     if (roleList.value.includes(data.dictActualitySurvey)) {
       message.error('请选择现状调查')
       return
     }
     if (!data.details.length) {
       message.error('至少要有一条变更项明细')
       return
     }
     console.log('data', data)
     //现状调查为是
     let flag = false
     data.details.map((item) => {
       if (roleList.value.includes(item.drawingNumber)) {
         message.error('图纸图号不能为空')
         flag = true
       }
       if (roleList.value.includes(item.dictAlertPlan)) {
         message.error('图纸变更方案不能为空')
         flag = true
       }
     })
     if (flag) return
     console.log('通过')
     formLoading.value = true
     try {
       if (type == 1) {
         if (formType.value === 'create') {
           await DesignAlertTicketApi.createDesignAlertTicket(data)
           message.success(t('common.createSuccess'))
         } else {
           await DesignAlertTicketApi.updateDesignAlertTicket(data)
           message.success(t('common.updateSuccess'))
         }
       } else {
         await DesignAlertTicketApi.submitDesignAlertTicket(data)
         message.success(t('common.updateSuccess'))
       }
       goBack()
     } finally {
       formLoading.value = false
     }
   }
   // 获得id
   const { query } = useRoute() // 路由的查询
   const contentHeight = ref(0)
   onMounted(async () => {
     formLoading.value = true
     formType.value = query.type
     //跳转携带参数
     console.log('query',query)
     if (query.type == 'jump') {
       const {
         id,
         taskNumber,
         productNumber,
         productName,
         partType,
         customerCode,
         customerName,
         productType,
         productStandard
       } = query
       formData.value.taskNumber = taskNumber
       formData.value.productNumber = productNumber
       formData.value.productName = productName
       formData.value.partType = partType
       formData.value.customerCode = customerCode
       formData.value.customerName = customerName
       formData.value.productType = productType
       formData.value.productStandard = productStandard
       formData.value.taskId = id
     }
     if (query.id) {
       formData.value = await DesignAlertTicketApi.getDesignAlertTicket(query.id)
     }
     contentHeight.value = document.body.clientHeight - 127
     formLoading.value = false
   })
</script>
<style scoped lang="scss">
   .contentView {
     padding: 10px;

     background: #fff;
     .orderTitle {
       width: 100%;
       line-height: 53px;
       position: relative;
       text-align: center;
       font-size: 30px;
       img {
         width: 232px;
         height: 53px;
         position: absolute;
         left: 0;
         top: 0;
       }
     }
   }
   .tableView {
     :deep(.el-input__wrapper) {
       box-shadow: 0 0 0 0px var(--el-input-border-color, var(--el-border-color)) inset;
       cursor: default;
       .el-input__inner {
         cursor: default !important;
         text-align: left;
       }
     }
   }
   .orderView {
     border: 1px solid #000;
     font-size: 14px;
     border-color: #000;
     :deep(.el-input__wrapper) {
       box-shadow: 0 0 0 0px var(--el-input-border-color, var(--el-border-color)) inset;
       cursor: default;
       .el-input__inner {
         cursor: default !important;
       }
     }
     .detailTitle {
       background: rgb(179, 255, 255);
       font-weight: bold;

       line-height: 30px;
       padding-left: 10px;
       border-bottom: 1px solid #000;
     }
     .detailItem {
       line-height: 30px;
       display: flex;
       align-items: center;
       border-bottom: 1px solid #000;
       .leftLabel {
         width: 110px;
         flex-shrink: 0;
         text-align: center;
         border-right: 1px solid #000;
         background: rgb(233, 251, 251);
       }
       .rightIpt {
         flex: 1;
         :deep(.is-focus) {
           border: none !important;
         }
       }
     }
     .detailItem + .detailItem {
       border-left: 1px solid #000;
     }
   }
</style>